﻿using System;
using PointOfSale.Global;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace PointOfSale.Class
{
	public class clsUnitConversion
	{
		private int itemId;
		private int srcUnitId;
		private int desUnitId;
		private double factor;

		public clsUnitConversion()
		{
			
		}

		#region Properties
		public int ItemId
		{
			get
			{
				return itemId;
			}
			set
			{
				itemId = value;
			}
		}
		public int SourceUnitId
		{
			get
			{
				return srcUnitId;
			}
			set
			{
				srcUnitId = value;
			}
		}
		public int DestUnitId
		{
			get
			{
				return desUnitId;
			}
			set
			{
				desUnitId = value;
			}
		}
		public double Factor
		{
			get
			{
				return factor;
			}
			set
			{
				factor = value;
			}
		}
		#endregion

		public void Add()
		{
			String strInsert = "INSERT tblUnitConversion(ItemId, UnitSourceId, UnitDestId, Factor) " + 
				"VALUES("		+	 
				itemId			+ ", " + 
				srcUnitId		+ ", " + 
				desUnitId		+ ", " +
				factor			+ ")";
			clsDatabase.ExecuteSQL(strInsert, clsGlobal.g_DataConn);	
		}
		public void delete(string deleteCommand)
		{
			clsDatabase.ExecuteSQL(deleteCommand, clsGlobal.g_DataConn);	
		}

		public static DataTable GetUnitForAnItem(int itemId)
		{
			string str="(select tblUnitConversion.unitSourceId as unitId, tblUnit.unitName from tblUnitConversion inner join tblUnit on tblUnit.unitId = tblUnitConversion.unitSourceId where itemId=" + itemId +") "
				+ "UNION (select tblUnitConversion.unitDestId as unitId, tblUnit.unitName from tblUnitConversion inner join tblUnit on tblUnit.unitId = tblUnitConversion.unitDestId where itemId=" + itemId +")";
			DataTable dt = clsDatabase.GetDataToTable(str, clsGlobal.g_DataConn);
			return dt;
		}

		public static double GetFactor(int itemId, int donViChuanId, int donViKhacId)
		{
			double dbSource = 0.0;
			if(donViChuanId == donViKhacId)
			{
				dbSource = 1;
			}
			else
			{
				string selectCommand = "select factor from tblUnitConversion "
					+ " where itemId = " + itemId
					+ " and unitSourceId = " + donViChuanId
					+ " and unitDestId = " + donViKhacId;
				DataTable dt = clsDatabase.GetDataToTable(selectCommand, clsGlobal.g_DataConn);
				if(dt.Rows.Count == 0)
				{
					dbSource = -1;
				}
				else
				{
					dbSource = Convert.ToDouble(dt.Rows[0][0]);
				}
			}
			return dbSource;
		}
	}
}
